package com.itheima.reggie.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Yan
 * @date 2022/2/27
 */
@Slf4j
@Component
public class TimedTask {

    @Autowired
    private DishService dishService;

    @Scheduled(cron = "0 0/10 * * * ?")
    public void deleteFile(){
        List<Dish> listImages = dishService.list();
        List<String> imageName = listImages.stream().map(Dish::getImage).collect(Collectors.toList());


        File file =new File("D:\\Develop\\myfile");
        log.info("定时任务执行了");
        File[] files = file.listFiles();


        if(ObjectUtils.isEmpty(files)){
            return;
        }
        List<String> fileName = Arrays.stream(files).map(File::getName).collect(Collectors.toList());

        boolean b = fileName.removeAll(imageName);
        //剩余的文件，数据库中没有，可以删除
        for (String s : fileName) {
            File file1 =new File("D:\\Develop\\myfile\\"+s);
            //boolean delete = file1.delete();
            FileUtils.deleteQuietly(file1);
        }
    }
}
